package com.wb.core12线程.练习;



/**
 * @author 黄衡熙
 * @version 1.0
 */
/*
*  定义两个线程分别打印不同的内容,要求两个线程之间交替执行10次
* 例如第一个线程打印Hello,第二个线程打印World
* 其结果为HelloWorldHelloWorldHelloWorldHelloWorld....
*或者WorldHelloWorldHelloWorldHelloWorldHello...
* */
public class Test {
    public static void main(String[] args) {
        Printer p1 = new Printer("Hello");
        Printer p2 = new Printer("World");
        p1.start();
        p2.start();
    }
    static class Num {
        public static int flag = 0;
        public static int count = 20;
        public static  Object LOCK = new Object();
    }
    static class Printer extends Thread {
        private  String word;
        public Printer(String word) {
            this.word = word;
        }
        @Override
        public void run() {
            while (true) {
                synchronized (Num.LOCK) {
                    if (Num.count == 0) {
                        break;
                    }
                    if ("Hello".equals(word) && Num.flag != 0) {
                        try {
                            Num.LOCK.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    else if ("World".equals(word) && Num.flag != 1) {
                        try {
                            Num.LOCK.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    } else {
                        System.out.print(word);
                        Num.count--;
                        Num.flag = 1 - Num.flag;
                        Num.LOCK.notifyAll();
                    }
                }
            }
        }
    }
}